import axios from 'axios';
import env from '../../build/env';
import semver from 'semver';
import packjson from '../../package.json';
import moment from 'moment';
// development 开发 production 生产
// http://47.113.179.102:8080
const ajaxUrl = process.env.NODE_ENV === 'development' ? 'https://www.diantangkeji.com/server/' : 'https://www.diantangkeji.com/server/'; //正式服务器
// const ajaxUrl = process.env.NODE_ENV === 'development' ? 'https://ohaigk.zjhlang.com' : 'https://ohaigk.zjhlang.com'; //测试
const QrcodeURL = 'http://111.231.118.185:9008/index.html'; //内网跳转的二维码地址
const noApiImg = "http://10.36.213.14:9007"; //内网图片用的域名
const benbiUPUrl = "https://www.diantangkeji.com/server/";
// http://192.168.3.234:8904/swagger/index.html
// development 开发 production 生产
// const ajaxUrl = process.env.NODE_ENV === 'development' ? 'http://192.168.3.234:8904' : 'http://192.168.3.234:8904';
// const QrcodeURL = 'http://192.168.3.234:8904/index.html'
// const noApiImg = "http://192.168.3.234:8904"
// const benbiUPUrl = "http://192.168.3.234:8904/api/"



const qiniuPublicTokenUrl = "/public/token";
const qiniuPrivateTokenUrl = "/private/token";
const qiniuImgDownUrl = "https://qnc.qjnice.com/";
const qiniuImgUpLoadUrl = 'https://upload.qiniup.com/';
axios.defaults.baseURL = ajaxUrl;
let util = {};
util.title = function (title) {
	title = title || '';
	window.document.title = title;
};
util.baseApi = {
	pageConfig: {
		indexName: 'index',
		sizeName: 'size'
	},
	ajaxUrl,
	QrcodeURL,
	benbiUPUrl,
	noApiImg,
	qiniuImgUpLoadUrl,
	qiniuImgDownUrl
};
util.inOf = function (arr, targetArr) {
	let res = true;
	arr.forEach(item => {
		if (targetArr.indexOf(item) < 0) {
			res = false;
		}
	});
	return res;
};

util.oneOf = function (ele, targetArr) {
	if (targetArr.indexOf(ele) >= 0) {
		return true;
	} else {
		return false;
	}
};
util.oneOfAttr = function (ele, targetArr, attrName) {
	let res = false;
	targetArr.forEach(item => {
		if (item[attrName] == ele[attrName]) {
			res = true;
		}
	});
	return res;
};
util.showThisRoute = function (itAccess, currentAccess) {
	if (typeof itAccess === 'object' && Array.isArray(itAccess)) {
		return util.oneOf(currentAccess, itAccess);
	} else {
		return itAccess === currentAccess;
	}
	// util.oneOf = function (ele, targetArr) {
	//   if (targetArr.indexOf(ele) >= 0) {
	//     return true;
	//   } else {
	//     return false;
	//   }
	// };
};

util.getRouterObjByName = function (routers, name) {
	if (!name || !routers || !routers.length) {
		return null;
	}
	// debugger;
	let routerObj = null;
	for (let item of routers) {
		if (item.name === name) {
			return item;
		}
		routerObj = util.getRouterObjByName(item.children, name);
		if (routerObj) {
			return routerObj;
		}
	}
	return null;
};

util.handleTitle = function (vm, item) {
	if (typeof item.title === 'object') {
		return vm.$t(item.title.i18n);
	} else {
		return item.title;
	}
};

util.setCurrentPath = function (vm, name) {
	let title = '';
	let isOtherRouter = false;
	vm.$store.state.app.routers.forEach(item => {
		if (item.children.length === 1) {
			if (item.children[0].name === name) {
				title = util.handleTitle(vm, item);
				if (item.name === 'otherRouter') {
					isOtherRouter = true;
				}
			}
		} else {
			item.children.forEach(child => {
				if (child.name === name) {
					title = util.handleTitle(vm, child);
					if (item.name === 'otherRouter') {
						isOtherRouter = true;
					}
				}
			});
		}
	});
	let currentPathArr = [];
	if (name === 'home_index') {
		currentPathArr = [{
			title: util.handleTitle(vm, util.getRouterObjByName(vm.$store.state.app.routers, 'home_index')),
			path: '',
			name: 'home_index'
		}];
	} else if ((name.indexOf('_index') >= 0 || isOtherRouter) && name !== 'home_index') {
		currentPathArr = [{
			title: util.handleTitle(vm, util.getRouterObjByName(vm.$store.state.app.routers, 'home_index')),
			path: '/home',
			name: 'home_index'
		},
		{
			title: title,
			path: '',
			name: name
		}
		];
	} else {
		let currentPathObj = vm.$store.state.app.routers.filter(item => {
			if (item.children.length <= 1) {
				return item.children[0].name === name;
			} else {
				let i = 0;
				let childArr = item.children;
				let len = childArr.length;
				while (i < len) {
					if (childArr[i].name === name) {
						return true;
					}
					i++;
				}
				return false;
			}
		})[0];
		if (currentPathObj.children.length <= 1 && currentPathObj.name === 'home') {
			currentPathArr = [{
				title: '首页',
				path: '',
				name: 'home_index'
			}];
		} else if (currentPathObj.children.length <= 1 && currentPathObj.name !== 'home') {
			currentPathArr = [{
				title: '首页',
				path: '/home',
				name: 'home_index'
			},
			{
				title: currentPathObj.title,
				path: '',
				name: name
			}
			];
		} else {
			let childObj = currentPathObj.children.filter((child) => {
				return child.name === name;
			})[0];
			currentPathArr = [{
				title: '首页',
				path: '/home',
				name: 'home_index'
			},
			{
				title: currentPathObj.title,
				path: '',
				name: currentPathObj.name
			},
			{
				title: childObj.title,
				path: currentPathObj.path + '/' + childObj.path,
				name: name
			}
			];
		}
	}
	vm.$store.commit('app/setCurrentPath', currentPathArr);

	return currentPathArr;
};

util.openNewPage = function (vm, name, argu, query) {
	let pageOpenedList = vm.$store.state.app.pageOpenedList;
	let openedPageLen = pageOpenedList.length;
	let i = 0;
	let tagHasOpened = false;
	while (i < openedPageLen) {
		if (name === pageOpenedList[i].name) { // 页面已经打开
			vm.$store.commit('app/pageOpenedList', {
				index: i,
				argu: argu,
				query: query
			});
			tagHasOpened = true;
			break;
		}
		i++;
	}
	if (!tagHasOpened) {
		let tag = vm.$store.state.app.tagsList.filter((item) => {
			if (item.children) {
				return name === item.children[0].name;
			} else {
				return name === item.name;
			}
		});
		tag = tag[0];
		if (tag) {
			tag = tag.children ? tag.children[0] : tag;
			if (argu) {
				tag.argu = argu;
			}
			if (query) {
				tag.query = query;
			}
			vm.$store.commit('app/increateTag', tag);
		}
	}
	vm.$store.commit('app/setCurrentPageName', name);
};

util.toDefaultPage = function (routers, name, route, next) {
	let len = routers.length;
	let i = 0;
	let notHandle = true;
	while (i < len) {
		if (routers[i].name === name && routers[i].children && routers[i].redirect === undefined) {
			route.replace({
				name: routers[i].children[0].name
			});
			notHandle = false;
			next();
			break;
		}
		i++;
	}
	if (notHandle) {
		next();
	}
};

util.fullscreenEvent = function (vm) {
	vm.$store.commit('app/initCachepage');
	vm.$store.commit('app/updateMenulist');
};
util.getqiniuToken = function (typeName) {
	return new Promise((resolve, reject) => {
		let url = typeName === "Public" ? qiniuPublicTokenUrl : qiniuPrivateTokenUrl;
		axios.get(url).then(data => {
			let qiniuObj = {
				token: data,
				creatTime: new Date().getTime()
			};
			localStorage.setItem(`${typeName}qiniu`, JSON.stringify(qiniuObj));
			resolve && resolve();

		});
	});
};
util.judgeqiniuToken = function (typeName) {
	return new Promise((resolve, reject) => {
		let nowtime = new Date().getTime(),
			qiniuObj = {};
		if (localStorage.getItem(`${typeName}qiniu`)) {
			qiniuObj = JSON.parse(localStorage.getItem(`${typeName}qiniu`));
			if (nowtime - qiniuObj.creatTime > 50 * 60 * 1000) {
				//离上一次创建token已经过了50分钟，重新获取
				this.getqiniuToken(typeName).then(resolve);
			} else {
				resolve && resolve();
			}
		} else {
			this.getqiniuToken(typeName).then(resolve);
		}


	});
};
util.uploadImgPublic = function (data) {
	return new Promise((resolve, reject) => {
		this.judgeqiniuToken('Public').then(() => {
			let Publicqiniu = JSON.parse(localStorage.getItem(`Publicqiniu`));
			data.append("token", Publicqiniu.token);
			this.upload(data).then((res) => {
				resolve(res);
			}).catch((err) => reject(err));
		});
	});

};
util.uploadImgPrivate = function (data) {
	return new Promise((resolve, reject) => {
		this.judgeqiniuToken('Private').then(() => {
			let Privateqiniu = JSON.parse(localStorage.getItem(`Privateqiniu`));
			data.append("token", Privateqiniu.token);
			this.upload(data).then((res) => {
				resolve(res.data.key);
			}).catch((err) => reject(err));
		});
	});
};
util.upload = function (data, targeturl = this.baseApi.qiniuImgUpLoadUrl) {
	return new Promise((resolve, reject) => {
		axios({
			method: "POST",
			url: targeturl,
			data,
			headers: {
				"content-type": "multipart/form-data"
			},
		}).then((res) => {
			if (targeturl == this.baseApi.qiniuImgUpLoadUrl) {
				let str = qiniuImgDownUrl + res.data.key;
				resolve(str);
			} else {
				resolve(res);
			}

		})
			.catch((err) => {
				reject(err);
			});
	});
};
util.resetData = function (...params) {
	let [vm, formName, modal] = params;
	vm.$refs[formName].resetFields();
	vm[modal] = false;
};
util.utcToTime = function (...params) {
	let [utcData, formatData = 'YYYY-MM-DD HH:mm:ss'] = params;
	if (utcData) return moment.unix(utcData).format(formatData);
	return '';

};
util.utcToTime1 = function (...params) {
	let [utcData, formatData = 'YYYY-MM-DD'] = params;
	if (utcData) return moment.unix(utcData).format(formatData);
	return "未审核";
};
util.addZero = function (val) {
	let n = val.toString();
	return n[1] ? val : '0' + val;
};
util.getSuffixName = function (str) {
	let index1 = str.lastIndexOf(".");
	let postf = str.substring(index1, str.length);
	return postf;
};
util.exportFile = function (url, name) {
	return new Promise((resolve, reject) => {
		axios({
			method: "get",
			url,
			data: {},
			responseType: "blob"
		}).then(res => {
			// 处理返回的文件流
			const content = res;
			const blob = new Blob([content.data]);
			let postf = this.getSuffixName(url);
			const fileName = `${name}${postf}`;
			if ("download" in document.createElement("a")) {
				// 非IE下载
				const elink = document.createElement("a");
				elink.download = fileName;
				elink.style.display = "none";
				elink.href = URL.createObjectURL(blob);
				document.body.appendChild(elink);
				elink.click();
				URL.revokeObjectURL(elink.href); // 释放URL 对象
				document.body.removeChild(elink);
				resolve && resolve();
			} else {
				// IE10+下载
				navigator.msSaveBlob(blob, fileName);
				resolve && resolve();
			}
		}).catch((err) => {
			reject && reject(err);
		});
	});

};
util.unqiue = function (array) {
	return [...new Set(array)];
};
//乘法函数，用来得到精确的乘法结果
util.mul = function (a, b) {
	var c = 0,
		d = a.toString(),
		e = b.toString();
	try {
		c += d.split(".")[1].length;
	} catch (f) { }
	try {
		c += e.split(".")[1].length;
	} catch (f) { }
	return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
};
//加法函数，用来得到精确的加法结果
util.add = function (a, b) {
	var c, d, e;
	try {
		c = a.toString().split(".")[1].length;
	} catch (f) {
		c = 0;
	}
	try {
		d = b.toString().split(".")[1].length;
	} catch (f) {
		d = 0;
	}
	return e = Math.pow(10, Math.max(c, d)), (this.mul(a, e) + this.mul(b, e)) / e;

};

//减法函数，用来得到精确的减法结果
util.sub = function (a, b) {
	var c, d, e;
	try {
		c = a.toString().split(".")[1].length;
	} catch (f) {
		c = 0;
	}
	try {
		d = b.toString().split(".")[1].length;
	} catch (f) {
		d = 0;
	}
	return e = Math.pow(10, Math.max(c, d)), (this.mul(a, e) - this.mul(b, e)) / e;

};
//除法函数，用来得到精确的除法结果
util.div = function (a, b) {
	var c, d, e = 0,
		f = 0;
	try {
		e = a.toString().split(".")[1].length;
	} catch (g) { }
	try {
		f = b.toString().split(".")[1].length;
	} catch (g) { }
	return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), this.mul(c / d, Math.pow(10, f - e));
};
util.extractAllObject = function (arr, brr = [], attributeName = 'children') {
	arr.forEach(item => {
		if (item[attributeName]) {
			let temp = JSON.parse(JSON.stringify(item));
			delete temp[attributeName];
			brr.push(temp);
			if (item[attributeName].length > 0) return this.extractAllObject(item[attributeName], brr);
		} else {
			brr.push(item);
		}
	});
	return brr;
};
util.filterArr = function (arr, targetArr, parent = null, compareName = 'name', attributeName = "children") {
	for (let i = 0; i < arr.length; i++) {
		let result = util.oneOfAttr(arr[i], targetArr, compareName); //判断元素的某个属性值是否相等 返回 true 和false
		if (result) {
			if (parent) {
				let temp = JSON.parse(JSON.stringify(parent));
				delete temp[attributeName];
				targetArr.push(temp);
			}
		}
		if (arr[i][attributeName] && arr[i][attributeName].length > 0) {
			this.filterArr(arr[i][attributeName], targetArr, arr[i]);
		}
	}
	return targetArr;
};
util.menuListOp = function (arr, targetArr, compareName = 'name', attributeName = 'children') {
	for (let i = 0; i < arr.length; i++) {
		let result = util.oneOfAttr(arr[i], targetArr, compareName); //判断元素的某个属性值是否相等 返回 true 和false
		if (result) {
			if (arr[i][attributeName] && arr[i][attributeName].length > 0) {
				this.menuListOp(arr[i][attributeName], targetArr);
			}
		} else {
			arr.splice(i, 1);
			i--;
		}
	}
	return arr;
};
util.treeGetArr = function (oriArr, ParentName = 'Parent', selfName = 'id', nameChange = "", allExpand = false, topid = 0) {
	let arr = [],
		testArr = JSON.parse(JSON.stringify(oriArr));
	for (let i = 0; i < testArr.length; i++) {
		testArr[i].children = [];
		if (nameChange) testArr[i][nameChange] = testArr[i].name;
		if (allExpand) testArr[i].expand = true;
		if (testArr[i].deep < 2) testArr[i].expand = true;
	}
	//分类
	for (let i = 0; i < testArr.length; i++) {
		for (let k = 0; k < testArr.length; k++) {
			if (testArr[i][ParentName] == testArr[k][selfName]) {
				testArr[k].children.push(testArr[i]);
			}
		}
	}
	//去重
	for (let i = 0; i < testArr.length; i++) {
		if (testArr[i][ParentName] == topid) {
			arr.push(testArr[i]);
		}
	}
	return arr;
};
util.deepCopy = function (oriObject) {
	return JSON.parse(JSON.stringify(oriObject));
};
util.on = (function () {
	if (document.addEventListener) {
		return function (element, event, handler) {
			if (element && event && handler) {
				element.addEventListener(event, handler, false);
			}
		};
	} else {
		return function (element, event, handler) {
			if (element && event && handler) {
				element.attachEvent('on' + event, handler);
			}
		};
	}
})();
util.off = (function () {
	if (document.removeEventListener) {
		return function (element, event, handler) {
			if (element && event) {
				element.removeEventListener(event, handler, false);
			}
		};
	} else {
		return function (element, event, handler) {
			if (element && event) {
				element.detachEvent('on' + event, handler);
			}
		};
	}
})();
util.validateForm = function (...params) {
	let [vm, formName] = params;
	return new Promise((re, rj) => {
		vm.$refs[formName].validate((valid) => {
			if (valid) {
				re && re();
			} else {
				rj && rj();
				vm.$Message.error('表单验证失败!');
			}
		});
	});
};
util.searchInit = function (...params) {
	let [vm, objectName] = params;
	const storeSearch = vm.$store.state.app.search[vm.$route.name];
	if (storeSearch) {
		const {
			search,
			page: {
				current,
				pageSize
			}
		} = storeSearch;
		vm.search = search;
		vm[objectName].current = current;
		vm[objectName].pageSize = pageSize;
	}
};
util.initRefresh = function (...params) {
	let [vm, refreshName = "refreshFn"] = params;
	vm.$store.commit("initRefresh");
	const storeRefresh = vm.$store.state.app.refresh.find(item => {
		return item.name == vm.$route.name;
	});
	storeRefresh.refreshFn = vm[refreshName];
};
util.getCurrentTitle = function (vm) {
	let title = "",
		obj = null;
	if (vm.$store.state.app.currentPath.length > 0) {
		obj = vm.$store.state.app.currentPath.find(item => {
			return item.name == vm.$store.state.app.currentPageName;
		});
		if (obj) title = obj.title;
	}
	return title;
};


export default util;
